package com.goldgov.mobile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.column.service.Column;
import com.goldgov.column.service.ColumnInit;
import com.goldgov.column.service.ColumnQuery;
import com.goldgov.column.service.ColumnService;
import com.goldgov.column.service.UserColumn;
import com.goldgov.column.service.UserColumnQuery;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.utils.PrintUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
/**
 * 
 * @author liziwen
 *
 */
@RestController
@RequestMapping("/mobile/column")
@Api("栏目接口")
public class ColumnForMobileController {

	@Autowired
	private ColumnService columnService;
	@Autowired
	private RemoteCallService remoteCallService;
	/**
	 * 获取所有栏目，并查出用户所选的栏目
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/getUserColumn")
	@ApiOperation(value = "查询用户栏目" )
	public JsonQueryObject<Column> getUserColumn(ColumnQuery query , HttpServletRequest request,Model model){
		LoginAuthUser user=LoginAuthUser.getUser(request);
		//LoginAuthUser user=LoginAuthUser.getUserTest(request);
		//查询所有栏目
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("categoryId", ColumnQuery.COLUMN_ALL);
		if(query.getSearchColumnTitle()!=null&& !"".equals(query.getSearchColumnTitle().trim())) {
			params.put("searchColumnTitle", query.getSearchColumnTitle());
		}else {
			params.put("searchColumnTitle", "");
		}
		//查询移动列表接口
		params.put("columnAttribute", 2);
		String resultList=remoteCallService.getForObject("findAllColumn", String.class, params);
		JSONObject json=JSONObject.parseObject(resultList);//.getJSONObject("page");
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; 
		JSONArray jsonList=json.getJSONArray("list");
		//List<Column> columnList=jsonList.toJavaList(Column.class);
		List<Column> columnList=JSONArray.parseArray(jsonList.toJSONString(),Column.class);
		//固定栏目
		Integer[] arraycolumn= {ColumnQuery.COLUMN_DJTT,ColumnQuery.COLUMN_ZSJJH,ColumnQuery.COLUMN_GCDT,ColumnQuery.COLUMN_ZYJS,ColumnQuery.COLUMN_GNDJYW,ColumnQuery.COLUMN_QNDJYW};
		if(user!=null) {
			UserColumnQuery userColumnQuery=new UserColumnQuery();
			userColumnQuery.setSearchUserId(user.getEntityID());
			userColumnQuery.setSearchType(UserColumnQuery.COLUMN_COL);
			userColumnQuery.setPageSize(-1);
			List<UserColumn> ucList =  columnService.findUserColumn(userColumnQuery);
			if(ucList!=null&& ucList.size()>0) {
				//不为空时加上关联userid
				for(Column column:columnList) {
					for(UserColumn userColumn:ucList) {
						if(column.getCategoryId().equals(userColumn.getColumnId())) {
							column.setUserId(userColumn.getUserId());
							column.setIsFocus(Column.FOCUS_YES);
							break;
						}else {
							column.setIsFocus(Column.FOCUS_NO);
						}
					}
				}
			}else {
				//为空时固定的栏目加userid
				for(Column column:columnList) {
					for(Integer col:arraycolumn) {
						if(col.equals(column.getCategoryId())) {
							column.setUserId(user.getEntityID());
							column.setIsFocus(Column.FOCUS_YES);//关注
							break;
						}else {
							column.setIsFocus(Column.FOCUS_NO);
						}
					}
				}
				//将固定栏目加入关联表中
				ColumnQuery columnQuery=new ColumnQuery();
				columnQuery.setSearchAddColumnIds(arraycolumn);
				columnQuery.setSearchUserID(user.getEntityID());
				columnQuery.setSearchType(UserColumnQuery.COLUMN_COL);
				columnService.upDateUserColumn(columnQuery);
			}
			query.setResultList(columnList);
		}else {
		//用户未登录下
		List<Column> list=new ArrayList<Column>();
			for(Column column:columnList) {
				for(Integer col:arraycolumn) {
					if(col.equals(column.getCategoryId())) {
						list.add(column);
						break;
					}
				}
			}
			query.setResultList(list);
		}
		
		return new JsonQueryObject<Column>(query);
	}
	/**
	 * 更新用户栏目
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@PostMapping("/updateUserColumn")
	@ApiOperation(value = "更新用户栏目" , notes = "传入参数为：栏目id数组")
	public void updateUserColumn(Integer[] columnIds,HttpServletRequest request,Model model,HttpServletResponse response){
		LoginAuthUser user=LoginAuthUser.getUser(request);
		//LoginAuthUser user=LoginAuthUser.getUserTest(request);
		if(columnIds != null&&user!=null &&columnIds.length>0 ) {
			try {
				ColumnQuery query =new ColumnQuery();
				query.setSearchAddColumnIds(columnIds);
				query.setSearchUserID(user.getEntityID());
				query.setSearchType(UserColumnQuery.COLUMN_COL);
				columnService.upDateUserColumn(query);
				model.addAttribute("msg", "更新成功");
				PrintUtil.print(response, true);;
			} catch (Exception e) {
				e.printStackTrace();
				model.addAttribute("msg", "更新失败,请联系管理员");
				PrintUtil.print(response, false);;
			}
		}else {
			model.addAttribute("msg", "更新失败");
			PrintUtil.print(response, false);;
		}
	}
	
	/**
	 * <党建头条>
	 * @author RongSL
	 * @version 1.0.0
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
//	@GetMapping("/getDjttByUser")
//	@ApiOperation(value = "根据用户查询党建头条" )
//	public JsonQueryObject<Column> getDjttByUser(@ApiIgnore ColumnQuery query , HttpServletRequest request,Model model){
//		LoginAuthUser user=LoginAuthUser.getUser(request);
//		query.setSearchUserID(user.getEntityID());
//		//查询个人经常访问栏目
//		List<Column> uclist=columnService.getLikeByUser(query);
//		List<Integer> idlist=new ArrayList<>();
//		if(!uclist.isEmpty()) {
//			//TODO 默认添加党建头条 为了解决爬取内容没有图片的问题而暂时添加
//			idlist.add(154);
//			//因为日志中存的是栏目中文名称，所以把栏目转换为ID
//			for(Column uc:uclist) {
//				if(CacheHolder.exist(uc.getModuleName())) {
//					idlist.add(Integer.valueOf(CacheHolder.get(uc.getModuleName()).toString()));
//				}
//			}
//		}
//		//删除党建头条
////		idlist.remove("154");
////		Map<String, Object> params=new HashMap<>();
////		params.put("pageSize", query.getPageSize());
////		params.put("pageNumber", request.getParameter("pageNumber"));
////		params.put("userId", user.getEntityID());
////		params.put("basicCategoryIds", idlist.toArray());
////		System.out.println("========="+idlist.toArray());
////		String resultList=remoteCallService.getForObject("findArticleList", String.class, params);
////		JSONObject json=JSONObject.parseObject(resultList);
////		List<Column> columnList=JSONArray.parseArray(json.getJSONArray("list").toJSONString(), Column.class);
////		query.setResultList(columnList);
//		return new JsonQueryObject<>(query);
//	}
	@GetMapping("/getDjttByUser")
	@ApiOperation(value = "根据用户查询党建头条" )
	public JsonObject<Object> getDjttByUser(@ApiIgnore ColumnQuery query , HttpServletRequest request,HttpServletResponse response,Model model){
		LoginAuthUser user=LoginAuthUser.getUser(request);
		query.setSearchUserID(user.getEntityID());
		//查询个人经常访问栏目
		List<Column> uclist=columnService.getLikeByUser(query);
		List<String> idlist=new ArrayList<>();
		if(!uclist.isEmpty()) {
			//TODO 默认添加党建头条 为了解决爬取内容没有图片的问题而暂时添加
			idlist.add(ColumnQuery.COLUMN_DJTT.toString());
			//因为日志中存的是栏目中文名称，所以把栏目转换为ID
			exit:for(Column uc:uclist) {
				if(ColumnInit.getCategorytitleconvertid().containsKey(uc.getModuleName())) {
					idlist.add(ColumnInit.getCategorytitleconvertid().get(uc.getModuleName()));
					if(uclist.size()==3) {
						break exit;
					}
				}
			}
		}else {
			idlist.add("154");
		}
		//删除党建头条
//		idlist.remove("154");
		JsonSuccessObject.SUCCESS.setData(idlist);
		return JsonSuccessObject.SUCCESS;
	}
}
